package com.mall.b2c.template.directive;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import com.mall.b2c.Constants;
import com.mall.b2c.hessian.StoreHessian;
import com.mall.common.ipseek.IPSeeker;
import com.mall.common.util.AppContext;
import org.springframework.stereotype.Repository;

import com.mall.b2c.bean.GoodsBean;
import com.mall.b2c.hessian.GoodsHessian;
import com.mall.common.directive.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 根据条件获取商品列表
 */
@Repository
public class GoodsListDirective extends BaseDirective {

	@Resource private GoodsHessian goodsHessian;
	@Resource
	protected StoreHessian storeHessian;
	@Resource protected IPSeeker ipSeeker;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Long goodsCategoryId = DirectiveUtils.getLong("cateId", params);
		String goodsCategoryCode = DirectiveUtils.getString("cateCode", params);
		Long tagId = DirectiveUtils.getLong("tagId", params);
		Long brandId = DirectiveUtils.getLong("brandId", params);
		Integer count = DirectiveUtils.getInt("count", params);
		Boolean hasStock = DirectiveUtils.getBool("hasStock", params);
		String orderBy = DirectiveUtils.getString("orderBy", params);
		if(hasStock == null){
			hasStock = true;
		}
		//TODO  商品若有会员价则此处需要获取会员id信息
		String json = goodsHessian.getGoodsListData(goodsCategoryId, goodsCategoryCode,
				brandId, tagId, count, hasStock, orderBy, null, getCurrStoreId());
		List<GoodsBean> goodsList = jsonToList(json, GoodsBean.class);
		renderParamToBody("goodsList", goodsList, env, body);
	}

	protected Long getCurrStoreId(){
		//自定义门店
		/*StoreBean store = (StoreBean) AppContext.getSessionAttr(Constants.CURR_STORE_SESSION_KEY);
		if(store == null ){
			IPLocation ipLocation = ipSeeker.getIPLocation(AppContext.getRemoteIp());//"125.110.94.53"
			String cityName = "";
			if(ipLocation != null){
				cityName = ipLocation.getCity();
			}
			store = jsonToObj(storeHession.getDefaultStore(cityName), StoreBean.class);
		}
		AppContext.setSessionAttr(Constants.CURR_STORE_SESSION_KEY, store);
		return store.getId();*/

		Cookie cookie = AppContext.getCookie(Constants.CURR_STORE_COOKIE_KEY);//选中门店
		Pattern pattern = Pattern.compile("\\d+");
		Long storeId = 1L;
		if(cookie != null && pattern.matcher(cookie.getValue()).matches()){//有选中城市
			storeId = Long.parseLong(cookie.getValue());
		}
		return storeId;
	}
}
